package com.sqk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqk.reggie.common.Result;
import com.sqk.reggie.dto.DishDto;
import com.sqk.reggie.pojo.Category;
import com.sqk.reggie.pojo.Dish;
import com.sqk.reggie.pojo.DishFlavor;
import com.sqk.reggie.service.CategoryService;
import com.sqk.reggie.service.DishFlavorService;
import com.sqk.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /*@Autowired
    private CacheManager cacheManager;*/


    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> selectPage(int page, int pageSize, String name) {
        //创建分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //创建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //添加排序查询
        queryWrapper.orderByDesc(Dish::getCreateTime);
        //执行分页查询,将所有的Dish都查出来
        dishService.page(dishPage, queryWrapper);
        //以上是将Dish的数据将进行封装


        //以下谁将DishDto的数据进行封装
        //Dish中没有 categoryName 字段，所以要将所有的Dish拷贝到DishDto中，并设置categoryName
        //使用BeanUtils工具类，springframework提供
        //参一：源数据source，参二：目标数据target，参三：排除字段(即：不拷贝该字段)
        //Page类中封装的 records 分页查询的所有数据(List<T>),此中是Dish的数据
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //获取所有Dish数据(即："records"字段)
        List<Dish> dishRecords = dishPage.getRecords();

        //将所有Dish数据封装到DishDto中
        List<DishDto> dishDtoList = dishRecords.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            //将所有Dish数据封装到DishDto中
            BeanUtils.copyProperties(item, dishDto);

            //根据Dish的categoryId字段获取Category
            Long categoryId = item.getCategoryId();

            //根据categoryId查询数据库获取category
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //获取category名称
                String categoryName = category.getName();

                //在DishDto中设置categoryName
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());  //将其转换为集合

        //将Page的records设置为DishDto数据
        dishDtoPage.setRecords(dishDtoList);

        //返回封装DishDto数据的分页查询
        return Result.success(dishDtoPage);
    }

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> saveDish(@RequestBody DishDto dishDto) {
        log.info("添加菜品 {}", dishDto);
        //执行自定义添加菜品操作
        dishService.saveWithFlavor(dishDto);

        //删除redis中的数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("添加成功!");
    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Transactional
    public Result<DishDto> getDishById(@PathVariable Long id) { //Dish数据id  //将Dish封装为DishDto

        DishDto dishDto = dishService.getDishById(id);

        return Result.success(dishDto);
    }

    /**
     * 修改菜品，同时保存对应的口味数据
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> updateDish(@RequestBody DishDto dishDto) {

        dishService.updateWithFlavor(dishDto);

        //清除redis中的菜品，根据key
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return Result.success("修改成功!");
    }


    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> removeDish(String ids) {
        log.info("ids = {}", ids);
        dishService.removeDishWithFlavor(ids);
        return Result.success("删除成功!");
    }

    /**
     * 修改菜品状态(起售，停售)
     *
     * @param ids
     * @param status
     * @return
     */
    @Transactional
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(String ids, @PathVariable Integer status) {
        //拆分ids
        String[] idsA = ids.split(",");

        Dish dish = new Dish();

        Arrays.stream(idsA).forEach(item -> {
            long dishId = Long.parseLong(item);
            dish.setId(dishId);
            dish.setStatus(status);
            dishService.updateById(dish);

            //根据dishId获取菜品
            Dish newDish = dishService.getDishById(Long.valueOf(item));
            String key = "dish_" + newDish.getCategoryId() + "_1";
            redisTemplate.delete(key);
        });


        return Result.success("修改成功!");
    }

    /**
     * 用于套餐中添加菜品的回显
     *
     * @param dish
     * @return
     */
    @Transactional
    @GetMapping("/list")
    public Result<Object> getCategoryList(Dish dish) {
        List<DishDto> dishDtoList = null;

        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        //先从redis中查询数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //如果有，直接返回
            return Result.success(dishDtoList);
        }

        if (StringUtils.isNotEmpty(dish.getName())) {
            LambdaQueryWrapper<Dish> queryWrapperName = new LambdaQueryWrapper<>();
            queryWrapperName.eq(Dish::getName, dish.getName());
            Dish one = dishService.getOne(queryWrapperName);
            return Result.success(one);
        }
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, 1);

        List<Dish> list = dishService.list(queryWrapper);
        dishDtoList = list.stream().map(item -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, item.getId());
            dishFlavorLambdaQueryWrapper.orderByDesc(DishFlavor::getCreateTime);
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

            dishDto.setFlavors(dishFlavors);

            return dishDto;
        }).collect(Collectors.toList());

        //如果没有，从数据库中查询，并将数据储存到redis中
        redisTemplate.opsForValue().set(key, dishDtoList);

        return Result.success(dishDtoList);
    }

}
